package com.android.example.app3;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateManager {
    private static final String TAG = "UpdateManager";
    private static final String DOWNLOAD_DIR = "app_updates";
    private static final String APK_NAME = "app_update.apk";
    private static final String CHECK_URL = "https://www.123865.com/s/X3Bkvd-o6OLh"; // 替换为你的版本检查接口
    private static final String DOWNLOAD_URL = "https://www.123865.com/s/X3Bkvd-E6OLh"; // 替换为百度网盘下载链接

    private Context context;
    private UpdateListener listener;

    public UpdateManager(Context context) {
        this.context = context;
    }

    public void setListener(UpdateListener listener) {
        this.listener = listener;
    }

    /**
     * 检查更新
     */
    public void checkForUpdate() {
        new Thread(() -> {
            try {
                // 1. 获取当前版本
                PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                String currentVersion = pInfo.versionName;

                // 2. 调用接口检查新版本
                HttpURLConnection conn = (HttpURLConnection) new URL(CHECK_URL).openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    // 解析接口返回的JSON（示例）
                    String response = readResponse(conn);
                    String latestVersion = parseLatestVersion(response); // 实现解析逻辑
                    String downloadUrl = parseDownloadUrl(response); // 从接口获取下载链接

                    // 3. 比较版本号
                    if (isNewVersion(latestVersion, currentVersion)) {
                        if (listener != null) {
                            listener.onUpdateAvailable(latestVersion, downloadUrl);
                        }
                    } else {
                        Log.d(TAG, "当前已是最新版本");
                    }
                }
            } catch (Exception e) {
                if (listener != null) {
                    listener.onUpdateFailed("检查更新失败: " + e.getMessage());
                }
            }
        }).start();
    }

    /**
     * 下载APK
     */
    public void downloadApk(String downloadUrl) {
        new Thread(() -> {
            try {
                // 1. 创建下载目录
                File dir = new File(Environment.getExternalStorageDirectory(), DOWNLOAD_DIR);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 2. 下载文件
                HttpURLConnection conn = (HttpURLConnection) new URL(downloadUrl).openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    File apkFile = new File(dir, APK_NAME);
                    FileOutputStream fos = new FileOutputStream(apkFile);

                    byte[] buffer = new byte[1024];
                    int len;
                    long total = conn.getContentLength();
                    long downloaded = 0;

                    while ((len = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        downloaded += len;
                        final int progress = (int) (downloaded * 100 / total);
                        if (listener != null) {
                            listener.onDownloadProgress(progress);
                        }
                    }

                    fos.flush();
                    fos.close();
                    is.close();

                    if (listener != null) {
                        listener.onInstallReady(apkFile);
                    }
                }
            } catch (Exception e) {
                if (listener != null) {
                    listener.onUpdateFailed("下载失败: " + e.getMessage());
                }
            }
        }).start();
    }

    /**
     * 安装APK
     */
    public void installApk(File apkFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // Android 7.0+ 使用FileProvider
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri contentUri = FileProvider.getUriForFile(
                    context,
                    context.getPackageName() + ".fileprovider",
                    apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        } else {
            // 旧版本
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }

    /**
     * 比较版本号（简单实现，实际项目建议使用专门的版本比较库）
     */
    private boolean isNewVersion(String latest, String current) {
        String[] latestParts = latest.split("\\.");
        String[] currentParts = current.split("\\.");

        for (int i = 0; i < Math.min(latestParts.length, currentParts.length); i++) {
            int latestVersion = Integer.parseInt(latestParts[i]);
            int currentVersion = Integer.parseInt(currentParts[i]);

            if (latestVersion > currentVersion) {
                return true;
            } else if (latestVersion < currentVersion) {
                return false;
            }
        }
        return false;
    }

    // 以下为辅助方法（需根据实际需求实现）
    private String readResponse(HttpURLConnection conn) throws Exception {
        // 实现读取HTTP响应的逻辑
        return "";
    }

    private String parseLatestVersion(String response) {
        // 实现解析JSON，提取最新版本号
        return "2.0.0";
    }

    private String parseDownloadUrl(String response) {
        // 实现解析JSON，提取下载链接
        return DOWNLOAD_URL;
    }

    public interface UpdateListener {
        void onUpdateAvailable(String versionName, String downloadUrl);

        void onUpdateFailed(String errorMsg);

        void onDownloadProgress(int progress);

        void onInstallReady(File apkFile);
    }
}
